package com.tmtc.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.tmtc.annotation.SystemControllerLog;
import com.tmtc.constant.MessageVar;
import com.tmtc.constant.ParameterConstant;
import com.tmtc.excelTools.ExcelUtils;
import com.tmtc.excelTools.JsGridReportBase;
import com.tmtc.excelTools.TableData;
import com.tmtc.frame.JsonResult;
import com.tmtc.frame.PageResult;
import com.tmtc.frame.ServiceException;
import com.tmtc.po.Driver;
import com.tmtc.po.DriverRepository;
import com.tmtc.service.DriverService;
import com.tmtc.utils.IdWorker;
import com.tmtc.utils.VerificationUtil;
import com.tmtc.utils.secret.MD5;
import com.tmtc.vo.DriverVo;

@Controller
@RequestMapping("/driver")
public class DriverController extends BaseController {
	@Autowired
	DriverService driverService;

	/**
	 * 添加和修改司机信息
	 * 
	 * @throws ServiceException
	 */
	@RequestMapping("/{edit}")
	@ResponseBody
	@SystemControllerLog("司机-编辑")
	public JsonResult insert(HttpServletRequest request, HttpServletResponse response, @PathVariable String edit,
			@RequestParam CommonsMultipartFile[] license_picFile, @RequestParam CommonsMultipartFile[] photoFile,
			@RequestParam CommonsMultipartFile[] bg_picFile, @Valid @ModelAttribute Driver driver,
			BindingResult bindingResult) throws ServiceException {
		if (bindingResult.hasErrors()) {
			super.handlerErrors(bindingResult);
		}
		if (edit.equals("add")) {
			DriverRepository driverRepository = new DriverRepository();
			driverRepository.or().andMobileEqualTo(driver.getMobile());
			if (driverService.count(driverRepository) > 0) {
				return new JsonResult(2, "司机手机号重复", null);
			}
			driver.setId(IdWorker.nextId());
			driver.setIs_check(ParameterConstant.IS_CHECK);
			driver.setCreate_time(new Date());
			String phone = driver.getMobile();
			if (0 >= VerificationUtil.length(phone)) {
				return new JsonResult(0, MessageVar.DRIVER_ADD_ERROR, null);
			}
			String password = phone.substring(phone.length() - 6, phone.length());
			String pw = MD5.makeMd5(password);
			driver.setPassword(pw);
			driverService.insert(driver, license_picFile, photoFile, bg_picFile, request);
			return new JsonResult();
		} else if (edit.equals("update")) {
			DriverRepository driverRepository = new DriverRepository();
			driverRepository.or().andMobileEqualTo(driver.getMobile()).andIdNotEqualTo(driver.getId());
			String id = driver.getId();
			if (null != id && "" != id) {
				driverService.update(driver, license_picFile, photoFile, bg_picFile, request);
				return new JsonResult();
			} else {
				return new JsonResult();
			}
		}
		return new JsonResult(0, MessageVar.DO_ERROR, null);
	}

	/**
	 * 重置密码
	 * 
	 * @param request
	 * @param response
	 * @param user_id
	 * @return
	 */
	@RequestMapping("/updatePassWord")
	@ResponseBody
	@SystemControllerLog("司机-重置密码")
	public JsonResult updatePassWord(HttpServletRequest request, HttpServletResponse response,
			@RequestParam String driver_id) {
		Driver driver = driverService.selectByPrimaryKey(driver_id);
		if (null != driver) {
			driverService.updatePassWord(driver);
			return new JsonResult(driverService.updatePassWord(driver), MessageVar.USER_RESETPASSWORD_SUCCESS, null);
		}
		return new JsonResult(0, MessageVar.USER_RESETPASSWORD_ERROR, null);
	}

	/**
	 * 删除司机信息
	 */
	@RequestMapping("/delete")
	@ResponseBody
	@SystemControllerLog("司机-删除")
	public JsonResult delete(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(required = true) String ids) {
		String[] idArr = ids.split(",");
		for (String id : idArr) {
			Driver driver = new Driver();
			driver.setId(id);
			driver.setIs_check(ParameterConstant.IS_NOT_CHECK);
			if (0 == driverService.update(driver)) {
				return new JsonResult(0, MessageVar.DELETE_ERROR, 0);
			}
		}
		return new JsonResult(1, MessageVar.DELETE_SUCCESS, 1);
	}

	/**
	 * 永久删除司机信息
	 */
	@RequestMapping("/forEver")
	@ResponseBody
	@SystemControllerLog("司机-永久删除")
	public JsonResult forEver(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(required = true) String ids) {
		String[] idArr = ids.split(",");
		for (String id : idArr) {
			if (0 == driverService.deleteForEver(id)) {
				return new JsonResult(0, MessageVar.DELETE_ERROR, 1);
			}
		}
		return new JsonResult(1, MessageVar.DELETE_SUCCESS, 1);
	}

	/**
	 * 司机列表
	 */
	@RequestMapping("/query")
	@ResponseBody
	@SystemControllerLog("司机-查询")
	public PageResult query(HttpServletRequest request, HttpServletResponse response, @RequestParam Integer page,
			@RequestParam Integer rows, @RequestParam(required = false) String mobile,
			@RequestParam(required = false) String real_name, @RequestParam(required = false) Integer city_id) {
		if (null != page && null != rows) {
			DriverRepository driverRepository = new DriverRepository();
			DriverRepository.Criteria criteria = driverRepository.createCriteria();
			driverRepository.setPageSize(rows);
			driverRepository.setRowIndex((page - 1) * rows);
			if (0 != VerificationUtil.length(mobile)) {
				criteria.andMobileLike("%" + mobile + "%");
			}
			if (0 != VerificationUtil.length(real_name)) {
				criteria.andReal_nameLike("%" + real_name + "%");
			}
			if (null != city_id) {
				criteria.andCity_idEqualTo(city_id);
			}
			criteria.andIs_checkEqualTo(ParameterConstant.IS_CHECK);
			return driverService.selectByPage(driverRepository);
		}
		return new PageResult(0, null, 0);
	}

	/**
	 * 司机列表
	 */
	@RequestMapping("/queryNotPage")
	@ResponseBody
	@SystemControllerLog("司机-查询/没分页")
	public JsonResult queryNotPage(HttpServletRequest request, HttpServletResponse response) {
		DriverRepository driverRepository = new DriverRepository();
		DriverRepository.Criteria criteria = driverRepository.createCriteria();
		criteria.andIs_checkEqualTo(ParameterConstant.IS_CHECK);
		JsonResult jsonResult = new JsonResult(1, "获取成功", driverService.select(driverRepository));
		return jsonResult;
	}

	/**
	 * 查询是否有此手机号
	 * 
	 * @param mobile
	 *            手机号
	 * @return
	 */
	@RequestMapping("/selectByPhone")
	@ResponseBody
	public JsonResult selectByPhone(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(required = false) String mobile) {
		DriverRepository driverRepository = new DriverRepository();
		DriverRepository.Criteria criteria = driverRepository.createCriteria();
		criteria.andIs_checkEqualTo(ParameterConstant.IS_CHECK);
		if (0 != VerificationUtil.length(mobile)) {
			if (VerificationUtil.checkMobilePhone(mobile)) {
				criteria.andMobileEqualTo(mobile);
				List<Driver> listDriver = driverService.select(driverRepository);
				if (0 != VerificationUtil.size(listDriver)) {
					return new JsonResult(0, MessageVar.PHONE_NUM_REPEAT, null);
				} else {
					return new JsonResult();
				}
			}
		}
		return new JsonResult(0, MessageVar.DRIVER_PHONE_NULL, null);
	}

	/**
	 * 查询是否有此身份证
	 * 
	 * @param idcord
	 *            身份证
	 * @return
	 */
	@RequestMapping("/selectByIdcard")
	@ResponseBody
	public JsonResult selectByIdcard(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(required = false) String idcard) {
		DriverRepository driverRepository = new DriverRepository();
		DriverRepository.Criteria criteria = driverRepository.createCriteria();
		criteria.andIs_checkEqualTo(ParameterConstant.IS_CHECK);
		if (0 != VerificationUtil.length(idcard)) {
			if (VerificationUtil.checkIdcard(idcard)) {
				criteria.andIdcardEqualTo(idcard);
				List<Driver> listDriver = driverService.select(driverRepository);
				if (0 != VerificationUtil.size(listDriver)) {
					return new JsonResult(0, MessageVar.DO_ERROR, null);
				} else {
					return new JsonResult();
				}
			}
		}
		return new JsonResult(0, MessageVar.DO_ERROR, null);
	}

	/**
	 * 查看图片
	 * 
	 * @param request
	 * @param response
	 * @param id
	 *            司机ID
	 * @return
	 */
	@RequestMapping("/selectById")
	@ResponseBody
	@SystemControllerLog("司机-查看图片")
	public JsonResult selectById(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(required = false) String id) {
		Map<String, List<String>> map = driverService.img(id);
		return new JsonResult(1, "", map);
	}

	/**
	 * 恢复使用
	 * 
	 * @param request
	 * @param response
	 * @param id
	 *            司机ID
	 * @return
	 */
	@RequestMapping("/updateRecover")
	@ResponseBody
	@SystemControllerLog("司机-恢复使用")
	public JsonResult updateRecover(HttpServletRequest request, HttpServletResponse response,
			@RequestParam String ids) {
		String[] idArr = ids.split(",");
		for (String id : idArr) {
			if (0 == driverService.updateRecover(id)) {
				return new JsonResult(0, MessageVar.ISCHECK_ERROR, 0);
			}
		}
		return new JsonResult(1, MessageVar.ISCHECK_SUCCESS, 1);
	}

	/**
	 * 司机导出
	 */
	@RequestMapping("/export")
	@ResponseBody
	@SystemControllerLog("司机导出")
	public void export(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(required = false) String ids) {
		String[] idArr = ids.split(",");
		List<String> listId = new ArrayList<String>();
		for (int i = 0; i < idArr.length; i++) {
			listId.add(idArr[i]);
		}
		DriverRepository driverRepository = new DriverRepository();
		DriverRepository.Criteria criteria = driverRepository.createCriteria();
		criteria.andIdIn(listId);
		criteria.andIs_checkEqualTo(ParameterConstant.IS_CHECK);
		List<DriverVo> list = driverService.selectDetail(driverRepository);
		String[] hearders = new String[] { "真实姓名", "手机号", "性别", "驾龄", "生日", "身份证", "驾照号", "籍贯", "住址", "司机来源", "所属城市",
				"是否有效" };
		String[] fields = new String[] { "real_name", "mobile", "gender", "driver_age", "birthday", "idcard",
				"license_no", "native_place", "address", "driver_source_name", "city_name", "is_check" };
		TableData td = ExcelUtils.createTableData(list, ExcelUtils.createTableHeader(hearders), fields);
		JsGridReportBase report = null;
		String title = "司机信息";
		try {
			report = new JsGridReportBase(request, response);
			report.exportToExcel(title, "", td);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
